//
//  ListenMoreRecommendTableViewController.m
//  瓜子电台
//
//  Created by lanou on 16/8/11.
//  Copyright © 2016年 YueZhang. All rights reserved.
//

#import "ListenMoreRecommendTableViewController.h"
#import "CarouselView.h"
#import "ViwepagerModel.h"
#import "XiaoBianMoreModel.h"
#import "XiaoBianMoreTableViewCell.h"
#import "RecommendRatingTableViewCell.h"
#import "RadioShangHaiModel.h"
#import "RadioShangHaiTableViewCell.h"
#import "TrackListDetailViewController.h"
#import "MoreRecommendTableViewController.h"
#import "ListenMoreModel.h"

@interface ListenMoreRecommendTableViewController ()

@property (nonatomic, strong) NSMutableArray *cellDataArray;

@property (nonatomic, strong) NSMutableArray *keyArray;

@property (nonatomic, strong) NSMutableArray *keyIdArray;

@end

@implementation ListenMoreRecommendTableViewController

- (NSMutableArray *)keyIdArray
{
    if (!_keyIdArray) {
        _keyIdArray = [[NSMutableArray alloc] init];
    }
    return _keyIdArray;
}

- (NSMutableArray *)keyArray
{
    if (!_keyArray) {
        _keyArray = [[NSMutableArray alloc] init];
    }
    return _keyArray;
}

- (NSMutableArray *)cellDataArray
{
    if (!_cellDataArray) {
        _cellDataArray = [[NSMutableArray alloc] init];
    }
    return _cellDataArray;
}

- (NSMutableArray *)carouselArray
{
    if (!_carouselArray) {
        _carouselArray = [[NSMutableArray alloc] init];
    }
    return _carouselArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.type isEqualToString:@"others"]) {
        [self requestRecommendData];
    }else {
        [self requestDataShangHai];
    }
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"XiaoBianMoreTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendRatingTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell_1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RadioShangHaiTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell_2"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)requestRecommendData
{
    NSString *url = @"http://mobile.ximalaya.com/mobile/discovery/v3/category/recommends?categoryId=1&contentType=album&device=iPhone&scale=2&statEvent=pageview%2Fcategory%40%E5%90%AC%E8%B5%84%E8%AE%AF&statModule=%E5%90%AC%E8%B5%84%E8%AE%AF_%E6%9B%B4%E5%A4%9A&statPage=tab%40%E5%8F%91%E7%8E%B0_%E6%8E%A8%E8%8D%90&statPosition=1&version=5.4.21";
    NSString *recomendUrl = [url stringByReplacingOccurrencesOfString:@"categoryId=1" withString:[NSString stringWithFormat:@"categoryId=%ld", self.categoryId]];
    [NetWorkrequestManage requestWithType:GET url:recomendUrl parameters:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        for (NSDictionary *imageDic in dic[@"focusImages"][@"list"]) {
            ViwepagerModel *model = [[ViwepagerModel alloc] init];
            [model setValuesForKeysWithDictionary:imageDic];
            [self.carouselArray addObject:model.pic];
        }
        for (NSDictionary *dataDic in dic[@"categoryContents"][@"list"]) {
            ListenMoreModel *model = [[ListenMoreModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.keyIdArray addObject:model];
            
            NSMutableArray *array = [[NSMutableArray alloc] init];
            for (NSDictionary *dict in dataDic[@"list"]) {
                XiaoBianMoreModel *model = [[XiaoBianMoreModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                [array addObject:model];
            }
            if (array.count > 0) {
                [self.keyArray addObject:dataDic[@"title"]];
                [self.cellDataArray addObject:array];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setHeaderView];
            [self.tableView reloadData];
        });
    } error:^(NSError *error) {
        NSLog(@"error");
    }];
}

- (void)requestDataShangHai
{
    NSString *urlStr = @"http://mobile.ximalaya.com/mobile/discovery/v1/city/recommendContent?code=43_310000_3100&device=iPhone&scale=2&version=5.4.21";
    [NetWorkrequestManage requestWithType:GET url:urlStr parameters:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        for (NSDictionary *imageDic in dic[@"focusImages"][@"list"]) {
            ViwepagerModel *model = [[ViwepagerModel alloc] init];
            [model setValuesForKeysWithDictionary:imageDic];
            [self.carouselArray addObject:model.pic];
        }
        for (NSInteger i = 0; i < [dic[@"content"][@"list"] count]; i++) {
            NSMutableArray *array = [[NSMutableArray alloc] init];
            if (i == 0) {
                for (NSDictionary *dataDic in dic[@"content"][@"list"][i][@"list"]) {
                    XiaoBianMoreModel *model = [[XiaoBianMoreModel alloc] init];
                    [model setValuesForKeysWithDictionary:dataDic];
                    [array addObject:model];
                }
            } else {
                for (NSDictionary *dataDic in dic[@"content"][@"list"][i][@"list"]) {
                    RadioShangHaiModel *model = [[RadioShangHaiModel alloc] init];
                    [model setValuesForKeysWithDictionary:dataDic];
                    [array addObject:model];
                }
            }
            if (array.count > 0) {
                [self.keyArray addObject:dic[@"content"][@"list"][i][@"title"]];
                [self.cellDataArray addObject:array];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setHeaderView];
            [self.tableView reloadData];
        });
        
    } error:^(NSError *error) {
        NSLog(@"error");
    }];
    
}



- (void)setHeaderView
{
    CarouselView *carouselView = [[CarouselView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 150) imageURLs:self.carouselArray];
    self.tableView.tableHeaderView = carouselView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.keyArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.cellDataArray[section] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XiaoBianMoreModel *model = self.cellDataArray[indexPath.section][indexPath.row];
    if ([self.type isEqualToString:@"听"] && indexPath.section == 1) {
        RadioShangHaiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_2" forIndexPath:indexPath];
        RadioShangHaiModel *model = self.cellDataArray[indexPath.section][indexPath.row];
        [cell setDataWithModel:model];
        return cell;
    } else {
        if (model.subtitle.length == 0) {
            XiaoBianMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
            [cell setDataWithModel:model];
            return cell;
        } else {
            RecommendRatingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_1" forIndexPath:indexPath];
            [cell setDataWithModel:model];
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.type isEqualToString:@"others"]) {
        XiaoBianMoreModel *model = self.cellDataArray[indexPath.section][indexPath.row];
        if (model.subtitle.length == 0) {
            return 105;
        } else {
            return 70;
        }
    } else {
        return 105;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 10)];
    grayView.backgroundColor = [UIColor grayColor];
    grayView.alpha = 0.3;
    [view addSubview:grayView];
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(5, 30, 10, 10)];
    imageV.image = [UIImage imageNamed:@"001"];
    [view addSubview:imageV];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(imageV.endX, 20, 180, 30)];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.text = self.keyArray[section];
    [view addSubview:titleLabel];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    button.frame = CGRectMake(kScreenWidth - 60, 20, 35, 30);
    
    [button setTitle:@"更多" forState:(UIControlStateNormal)];
    button.tag = section + 1;
    [button addTarget:self action:@selector(btnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [view addSubview:button];
    
    UIImageView *moreImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - 25, 30, 10, 10)];
    moreImage.image = [UIImage imageNamed:@"右边"];
    [view addSubview:moreImage];
    return view;
}

- (void)btnClick:(UIButton *)button
{
    
    if ([self.type isEqual: @"听"]) {
        if (button.tag == 1) {
            MoreRecommendTableViewController *vc = [[MoreRecommendTableViewController alloc] init];
            vc.type = @"first";
            vc.categoryId = self.categoryId;
            vc.str = self.keyArray[button.tag - 1];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            
        }
    } else {
        {
            NSString *str = self.keyArray.firstObject;
            if ([str isEqual: @"排行榜"]) {
                if (button.tag == 2) {
                    MoreRecommendTableViewController *vc = [[MoreRecommendTableViewController alloc] init];
                    vc.type = @"first";
                    vc.categoryId = self.categoryId;
                    vc.str = self.keyArray[button.tag - 1];
                    [self.navigationController pushViewController:vc animated:YES];
                } else {
                    MoreRecommendTableViewController *vc = [[MoreRecommendTableViewController alloc] init];
                    vc.type = @"others";
                    vc.categoryId = self.categoryId;
                    for (NSInteger i = self.keyIdArray.count - 1; i >= 0; i--) {
                        ListenMoreModel *model = self.keyIdArray[i];
                        if (model.keywordId == 0) {
                            [self.keyIdArray removeObject:model];
                        }
                    }
                    ListenMoreModel *model = self.keyIdArray[button.tag - 3];
                    vc.keywordId = model.keywordId;
                    vc.str = self.keyArray[button.tag - 1];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        }
    }
    
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ([self.keyArray[section] isEqualToString:@"排行榜"]) {
        return 0;
    }
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.type isEqual: @"others"]) {
        if (indexPath.section > 0) {
            XiaoBianMoreModel *model = self.cellDataArray[indexPath.section][indexPath.row];
            TrackListDetailViewController *vc = [[TrackListDetailViewController alloc] init];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
    } else {
        if (indexPath.section == 0) {
            XiaoBianMoreModel *model = self.cellDataArray[indexPath.section][indexPath.row];
            TrackListDetailViewController *vc = [[TrackListDetailViewController alloc] init];
            vc.model = model;
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            
        }
    }
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
